/**
 *******************************************************************************
 * \brief   CAS EBX Project Work "Kaffeemaschine"
 *
 * \file    writeToChannel.c
 * \version 1.0
 * \date    11.07.2010
 * \author  Baehler Thomas, Liechti Beat, Sauter Marc
 * \author  Vuksic Valentina, Zbinden Rene
 * 
 * \details	writes to channel
 * \details build with: 
 * \details gcc channel.c writeToChannel.c -o writeToChannel -lrt
 * \details then run with (example):
 * \details writeToChannel <chname:string> <value:int>
 *
 * \remark  Last Modifications:
 * \remark  V1.0, 11.07.2010   Initial release
 *******************************************************************************
 **/

#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// -- required for inet_aton when not using makefile???
//#define __USE_MISC

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//#include <sys/sendfile.h>
#include <sys/wait.h>
#include <time.h>
#include <sys/times.h>
#include <sched.h>

#include "channel.h"

#define RETCODE_SUCCESS		0
#define RETCODE_ERROR		-1

void usage(char *progname)
{
	printf("usage:\n\t%s <name of channel> <value>\n", progname);
}

int main(int argc, char** argv)
{
	int retCode = -1;
	if (argc == 3)
	{
		// -- expecting a string argv[1]
		char *channelName = argv[1];
		// -- expecting an int in argv[2]
		int value;
		if (sscanf(argv[2], "%d", &value) != 1)
		{
			printf("ERROR: value is not an int, aborting\n");
		}
		else
		{
			tChannel *channel = openChannelWrite(channelName, sizeof(int));
			if (channel == NULL)
			{
				printf("ERROR: could not open channel for writing, aborting\n");
			}
			else
			{
				int bytesWritten = writeChannel(channel, &value);
				if (bytesWritten != sizeof(int))
				{
					printf("ERROR: writeChannel returned unexpected code %d\n", bytesWritten);
				}
				else
				{
					printf("writeChannel wrote value %d to channel %s\n", value, channelName);
					retCode = 0;
				}
				closeChannel(channel);
			}
		}
	}
	else
	{
		usage(argv[0]);
	}
	return retCode;
}
